﻿using System;
using System.Xml;
using System.Xml.XPath;
using Syfuhs.APIWrappers.LiveMeeting.Exceptions;

namespace Syfuhs.APIWrappers.LiveMeeting
{
    public static class ErrorHandler
    {
        public static IXPathNavigable CheckForError(IXPathNavigable xmlDoc)
        {
            if (xmlDoc == null)
                throw new ArgumentNullException("xmlDoc");

            XmlNodeList nodeList = (xmlDoc as XmlDocument).SelectNodes("PlaceWareConfCenter/Fault");

            if (nodeList.Count > 0)
                HandleError(xmlDoc);

            return xmlDoc;
        }

        /// <summary>
        /// Error handler
        /// </summary>
        /// <param name="doc">Response document with error</param>
        public static void HandleError(IXPathNavigable errorDoc)
        {
            if (errorDoc == null)
                throw new ArgumentNullException("errorDoc");

            XmlNode node = (errorDoc as XmlDocument).SelectSingleNode("PlaceWareConfCenter/Fault");

            string faultCode = node.SelectSingleNode("FaultCode").InnerText.Replace(".", "");
            string faultMessage = node.SelectSingleNode("FaultString").InnerText;

            switch (faultCode) // just handle the uglier stuff first
            {
                case "ClientAuthentication":
                    throw new ClientAuthenticationException(faultMessage);

                case "ClientBadSyntaxBadFormat":
                    throw new ClientBadSyntaxBadFormatException(faultMessage);

                case "ClientBadSyntaxBadType":
                    throw new ClientBadSyntaxBadTypeException(faultMessage);

                case "ClientBadSyntaxNull":
                    throw new ClientBadSyntaxNullException(faultMessage);

                case "ServerInternalError":
                    throw new ServerInternalErrorException(faultMessage);

                case "ServerOperationUnavailableLicense":
                    throw new ServerOperationUnavailableLicenseException(faultMessage);

                case "ServerOperationUnavailableNotImplemented":
                    throw new ServerOperationUnavailableNotImplementedException(faultMessage);

                case "ServerOperationUnavailableNotImplementedVersion":
                    throw new ServerOperationUnavailableNotImplementedVersionException(faultMessage);

                default:
                    throw new LiveMeetingException(faultCode + ": " + faultMessage);
            }
        }
    }
}
